package wechat

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"hft/db/mongodb/model/wechat"
	"hft/e"
	"hft/global"
	"hft/tools/weixin/api"
	"hft/tools/weixin/model"

	"github.com/bytedance/sonic/encoder"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"golang.org/x/net/html"
)

type WeChat struct{}

// 关注时回复设置
func (*WeChat) ReplyWhenSubscribe(data wechat.SubscribeReply) (err error) {
	data.Tag = "subscribe"
	var opera = global.OC_MON.Database("wechat").Collection("subscribe_reply")
	res := opera.FindOne(context.TODO(), bson.D{{Key: "tag", Value: data.Tag}})
	if res.Err() != nil {
		// 找不到就插入
		_, err = opera.InsertOne(context.TODO(), data)
		if err != nil {
			return errors.New(e.ErrorInfo)
		}
		return nil
	}

	var filter = bson.D{{Key: "tag", Value: data.Tag}}
	var update = bson.D{
		{Key: "$set", Value: bson.D{
			{Key: "is_open", Value: data.IsOpen},
			{Key: "msg_type", Value: data.MsgType},
			{Key: "content", Value: data.Content},
			{Key: "image", Value: data.Image},
			{Key: "video", Value: data.Video},
			{Key: "voice", Value: data.Voice},
			{Key: "article_count", Value: data.ArticleCount},
			{Key: "articles", Value: data.Articles},
		}},
	}
	err = opera.FindOneAndUpdate(context.TODO(), filter, update).Err()
	fmt.Println(err)
	if err != nil {
		fmt.Println(3, err.Error())
		return errors.New(e.ErrorInfo)
	}
	return nil
}

// 添加菜单
func (*WeChat) CreateMenu(data *model.CustomMenu) (err error) {
	// 添加菜单
	err = api.WeiXinMenu.CreateMenu(data)
	var buttonList = make([]wechat.Button, 0)
	for _, v := range data.Buttons {
		buttonList = append(buttonList, wechat.Button{
			Name:      v.Name,
			Type:      v.Type,
			Key:       v.Key,
			Url:       v.Url,
			MediaID:   v.MediaID,
			AppID:     v.AppID,
			PagePath:  v.PagePath,
			ArticleID: v.ArticleID,
			ImgUrl:    v.ImgUrl,
			Level:     v.Level,
			PKey:      "",
			Message:   "",
		})
		if len(v.SubButton) != 0 {
			for _, j := range v.SubButton {
				buttonList = append(buttonList, wechat.Button{
					Name:      j.Name,
					Type:      j.Type,
					Key:       j.Key,
					Url:       j.Url,
					MediaID:   j.MediaID,
					AppID:     j.AppID,
					PagePath:  j.PagePath,
					ArticleID: j.ArticleID,
					ImgUrl:    j.ImgUrl,
					Level:     j.Level,
					PKey:      v.Key,
					Message:   html.UnescapeString(j.Message),
				})
			}
		}
	}
	// // 删除多条
	global.OC_MON.Database("wechat").Collection("wechat_menu").DeleteMany(context.TODO(), bson.M{})
	// fmt.Println("删除", err.Error())
	docs := make([]interface{}, len(buttonList))
	for i, button := range buttonList {
		docs[i] = button
	}
	global.OC_MON.Database("wechat").Collection("wechat_menu").InsertMany(context.TODO(), docs)
	return nil
}

// 查询菜单
func (*WeChat) GetMenu() (data []model.Button, err error) {

	var menuList = make([]model.Button, 0)
	var menuItem model.Button
	cursor, err := global.OC_MON.Database("wechat").Collection("wechat_menu").Find(context.TODO(), bson.M{})
	if err != nil {
		fmt.Println(err)
		return nil, mongo.ErrNoDocuments
	}
	var results []bson.M
	if err = cursor.All(context.TODO(), &results); err != nil {
		panic(err)
	}
	for _, result := range results {
		v, err := encoder.Encode(result, encoder.SortMapKeys)
		if err != nil {
			fmt.Printf("%v\n", err)
		}
		json.Unmarshal(v, &menuItem)
		menuList = append(menuList, menuItem)
	}
	// 构建菜单
	return menuList, nil
}

// 获取关注是回复
func (*WeChat) GetSubscribeReply() (data *wechat.SubscribeReply, err error) {
	var replyMsg *wechat.SubscribeReply
	err = global.OC_MON.Database("wechat").Collection("subscribe_reply").FindOne(context.TODO(), bson.D{{Key: "tag", Value: "subscribe"}}).Decode(&replyMsg)
	if err != nil {
		fmt.Println(err)
		return nil, errors.New(e.ErrorInfo)
	}
	return replyMsg, nil
}

var WeChatService = new(WeChat)
